﻿#region 命名空间

using System;

#endregion

namespace Sharp.Infrastructure
{
    /// <summary>
    ///     数据类型转换
    /// </summary>
    /// <remarks>解决自带的一下转换的繁琐性</remarks>
    public class ConvertHelper
    {
        /// <summary>
        ///     转换
        /// </summary>
        /// <param name="value">值</param>
        /// <param name="type">类型</param>
        /// <returns></returns>
        public static object ChangeType(object value, Type type)
        {
            if (value == null && type.IsGenericType)
                return Activator.CreateInstance(type);
            if (type == typeof (Guid))
                return new Guid(value as string);

            if (type == typeof (bool))
                return Convert.ToBoolean(value);


            if (value == null)
                return null;
            if (type == value.GetType())
                return value;
            if (type.IsEnum)
            {
                if (value is string)
                    return Enum.Parse(type, value as string);
                else
                    return Enum.ToObject(type, value);
            }
            if (!type.IsInterface && type.IsGenericType)
            {
                Type innerType = type.GetGenericArguments()[0];
                object innerValue = ChangeType(value, innerType);
                return Activator.CreateInstance(type, new object[] {innerValue});
            }

            if (!(value is IConvertible))
                return value;
            return Convert.ChangeType(value, type);
        }
    }
}